#include <iostream>
#include <vector>
#include <algorithm>

// 观察者接口
class Observer {
    public:
    virtual void update(const std::string& message) = 0;  // 纯虚函数
    virtual ~Observer() = default;
};

// 主题接口
class Subject {
    public:
    virtual void attach(Observer* observer) = 0;
    virtual void detach(Observer* observer) = 0;
    virtual void notify(const std::string& message) = 0;
    virtual ~Subject() = default;
};


// 具体主题
class ConcreteSubject : public Subject {
    private:
    std::vector<Observer*> observers;

    public:
    void attach(Observer* observer) override {
        observers.push_back(observer);
    }

    void detach(Observer* observer) override {
        observers.erase(std::remove(observers.begin(), observers.end(), observer), observers.end());
    }

    void notify(const std::string& message) override {
        for (auto observer : observers)
        {
            observer->update(message);
        }
    }

    void doSomethingImportant() {
        // 业务逻辑
        notify("Something important happened!");
    }
};

// 具体观察者
class ConcreteObserver : public Observer {
    private:
    std::string name;

    public:

    ConcreteObserver(const std::string& name) : name(name) {}

    void update(const std::string& message) override {
        std::cout << name << "recived message: " << message << std::endl;
    }
};

int main() {
    ConcreteSubject subject;
    ConcreteObserver observer1("Observer 1");
    ConcreteObserver observer2("Observer 2");

    subject.attach(&observer1);
    subject.attach(&observer2);

    subject.doSomethingImportant();

    subject.detach(&observer1);
    subject.doSomethingImportant();

    return 0;
}

